//
//  WLLComposeViewController.swift
//  WLLWeibo
//
//  Created by 王乐乐 on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class WLLComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
     //MARK: - 设置视图
   private func setupUI () {
        view.backgroundColor = UIColor.whiteColor()
    
        setupNAv()
    
    //添加控件
    //添加 textView
    view.addSubview(composeTextView)
    //添加 底部视图
    view.addSubview(composeBottomView)
    //添加 图片 view
    composeTextView.addSubview(composePictureView)
    
    //添加约束
    // 01 textView
    composeTextView.snp_makeConstraints { (make) in
        make.edges.equalTo(view).offset(UIEdgeInsetsZero)
    }
    //02 bottomView
    composeBottomView.snp_makeConstraints { (make) in
        make.leading.bottom.trailing.equalTo(view)
        make.height.equalTo(44)
    }
    //03 pictureView
    composePictureView.snp_makeConstraints { (make) in
        make.top.equalTo(composeTextView).offset(100)
        make.size.equalTo(CGSize(width: KSCREENW - 20, height: KSCREENW - 20))
        make.centerX.equalTo(composeTextView)
    }
    
    
     //MARK: - 监听底部按钮的点击  ...闭包的实例化
    composeBottomView.closure = {[weak self] (type : WLLComposeBottomViewType)->() in
        //闭包执行
        switch type {
        case .Picture:
            print("图片")
            self?.selectImages()
        case .Mention:
            print("@")
        case .Trend:
            print("#")
        case .Emoticon:
            print("笑脸")
            self?.switchKeyboard()
        case .Add:
            print("+")
        
        }
        
    }
     //MARK: - pictureView的闭包回调
    composePictureView.closure = {[weak self] in
        self?.selectImages()
    }
    
     //MARK: - 注册通知  监听键盘将要改变frame
    
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    
    }
    
    /**
     监听键盘 frame 的改变
     */
    func keyboardWillChangeFrame(noti:NSNotification) {
//       print(noti)
        //动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        //判断他是否为 nil, 是否可以转成 NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        
        //获取 CGRect
        let newRect = rect.CGRectValue()
        //更新约束
        composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - KSCREENH)
        }
        
        //设置动画
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
        
    }
    
    
     //MARK: - 设置导航
   private func setupNAv()  {
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
    //设置不能点击
    navigationItem.rightBarButtonItem?.enabled = false
    
    navigationItem.titleView = titleView
    
    }
     //MARK: - 监听事件
   @objc func cancelAction(){
    //取消第一响应者
    composeTextView.resignFirstResponder()
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: - 发布
   @objc func sendAction() {
        print("发布按钮点击")
    composePictureView.imageList.count == 0 ? update_text() : upload_pic()
    


//    NSNotificationCenter.defaultCenter().postNotificationName("lele", object: nil)
    
    cancelAction()
    
    //TODO:点击发布按钮之后,发布完成之前,发布按钮不可点击..-->  这里的逻辑机制暂时被认为是回到首页.但是实际的微博是回到当前页
    }
    
     //MARK: - 懒加载控件
    private lazy var titleView : UILabel = {
        //用户昵称
         let name = WLLUserAccountViewModel.shareTool.userAccount!.screen_name!
        //显示内容
        let str = "发微博\n\(name)"
        //获取范围
        let range = (str as NSString).rangeOfString(name)
        //初始化一个副文本
        let attr = NSMutableAttributedString(string: str)
        //设置副文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor , NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.attributedText = attr
        //如果不设置,则不显示
        lab.sizeToFit()
         return lab
        
    }()
    
        /// 自定义 textview
    private lazy var composeTextView :WLLComposeTextView = {
        let view = WLLComposeTextView()
        //设置代理
        view.delegate = self
        
        view.font = UIFont.systemFontOfSize(16)
        
        view.placeholder = "lelesosmartsocoolsocutesoclever"
        //允许上下滚动
        view.alwaysBounceVertical = true
        return view
    }()
    ///自定义底部视图
    private lazy var composeBottomView : WLLComposeBottomView = WLLComposeBottomView()
        /// 配图
    private lazy var composePictureView : WLLComposePictureView = WLLComposePictureView()
    //自定义表情键盘
    private lazy var emoticonKeyBoard : WLLEmoticonKeyboardView =  WLLEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: KSCREENW, height: 216 ))
    
}


 //MARK: - 发布微博
extension WLLComposeViewController{
    /**
     发布文字微博
     */
    func update_text() {
        
        WLLNetTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) in
            NSNotificationCenter.defaultCenter().postNotificationName("lele", object: nil)
//
//            self.cancelAction()
            SVProgressHUD.showSuccessWithStatus("发布成功了")
            
            }) { (error) in
                SVProgressHUD.showErrorWithStatus("发布失败了")
        }
        
    }
    /**
     发布带配图的微博
     */
    func upload_pic() {
        
       WLLNetTools.sharedTools.composeUpload(composeTextView.text, images:composePictureView.imageList , success: { (response) in
        NSNotificationCenter.defaultCenter().postNotificationName("lele", object: nil)
        
//        self.cancelAction()
        SVProgressHUD.showSuccessWithStatus("发布成功了")
        
        }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败了")
            
        }
        
    }
    
    
    
    
    
}


 //MARK: - 处理 BottomView 按钮的事件
extension WLLComposeViewController{
    
    func selectImages() {
        let pickerVc = UIImagePickerController()
        //设置代理
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
        
    }
     //MARK: - 切换键盘
    func switchKeyboard() {
        
        if composeTextView.inputView == nil {//此时是系统键盘
            //切换到表情键盘
            composeTextView.inputView = emoticonKeyBoard
             composeBottomView.isEmoticon = true
            
        }else{//此时是表情键盘
            //切换到系统键盘
            composeTextView.inputView = nil
            composeBottomView.isEmoticon = false
        }
        //刷新
        composeTextView.reloadInputViews()
        //成为第一响应者
        composeTextView.becomeFirstResponder()
    }

}

 //MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
//这里得遵循两个代理
extension WLLComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    // 该方法 苹果不建议使用了 但是你可以用
    //    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    //        print(image)
    //        composeTextView.backgroundColor = UIColor(patternImage: image)
    //        // 关闭控制器
    //        picker.dismissViewControllerAnimated(true, completion: nil)
    //    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
//        print(info)
//        
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //写到桌面上
//        let image1 = dealImageScale(image, width: 600)
//                let data = UIImagePNGRepresentation(image1)
//                data?.writeToFile("/Users/wanglele/Desktop/哈哈.png", atomically: false)
//
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        //"外界赋值"
        composePictureView.addImages(UIImage.dealImageScale(image, width: 600))
        //关闭控制
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
 

    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("取消了")
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
  
    
}



 //MARK: - UITextViewDelegate
extension WLLComposeViewController : UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        //没有文本,右侧按钮不可点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //滚动时取消键盘第一响应
        self.composeTextView.resignFirstResponder()
    }
}














